package com.aabte.design2.structural.proxy;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 为了节省网络带宽，我们可以将请求结果缓存下来并保存一段时间。但你可能无
 * 法直接将这些代码放入服务类中。比如该类可能是第三方程序库的一部分或其签
 * 名是`final（最终）`。因此我们会在一个实现了服务类接口的新代理类中放入
 * 缓存代码。当代理类接收到真实请求后，才会将其委派给服务对象。
 *
 * @author Daniel
 * @version 1.0
 * @date 2020/5/3
 */
public class CachedTV implements RemotePartyTVLib {

    private RemotePartyTVLib service;

    private Collection<Video> listCached;

    private Map<Integer, Video> videoInfoCached = new LinkedHashMap<>();
    private Map<Integer, String> videoCached = new LinkedHashMap<>();

    private boolean needReset;

    public CachedTV(RemotePartyTVLib service) {
        this.service = service;
    }

    @Override
    public Collection<Video> listVideos() {
        if (null == listCached || needReset) {
            listCached = service.listVideos();
        } else {
            System.out.println("get videos success from cache. videos = " + listCached);
        }
        return listCached;
    }

    @Override
    public Video getVideoInfo(int id) {
        if (needReset) {
            return service.getVideoInfo(id);
        }
        Video videoInfo = videoInfoCached.get(id);
        if (null == videoInfo) {
            videoInfo = service.getVideoInfo(id);
        } else {
            System.out.println("get videoInfo success from cache. videoInfo = " + videoInfo);
        }
        if (null != videoInfo) {
            videoInfoCached.put(id, videoInfo);
        }
        return videoInfo;
    }

    @Override
    public String downloadVideo(int id) {
        if (null == videoCached || needReset) {
            return service.downloadVideo(id);
        }
        String video = videoCached.get(id);
        if (null == video) {
            video = service.downloadVideo(id);
        } else {
            System.out.println("get video success from cache. video = " + video);
        }
        if (null != video) {
            videoCached.put(id, video);
        }
        return video;
    }
}
